#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

void *rontine(void *arg)
{
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);

    struct sockaddr_in myaddr;
    bzero(&myaddr, sizeof(myaddr));
    myaddr.sin_family = AF_INET;
    myaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    myaddr.sin_port = htons(60001);

    bind(sockfd, (struct sockaddr *)&myaddr, sizeof(myaddr));

    char buf[128];
    struct sockaddr_in peeraddr;
    socklen_t len = sizeof(peeraddr);

    printf("[%s : %hu]", inet_ntoa(myaddr.sin_addr), myaddr.sin_port);
    while(1)
    {
        // printf("开启线程\n");
        bzero(&peeraddr, sizeof(peeraddr));
        bzero(buf, sizeof(buf));
        recvfrom(sockfd, buf, sizeof(buf), 0, (struct sockaddr *)&peeraddr, &len);
        printf("[%s : %hu]-->%s", inet_ntoa(peeraddr.sin_addr), peeraddr.sin_port, buf);
    }
} 

int main(int argc, char const *argv[])
{
    if(argc != 3)
    {
        printf("argv[1] : sockaddr, argv [2] : post\n");
        exit(0);
    }

    pthread_t tid;
    pthread_create(&tid, NULL, rontine, (void *)argv[2]);

    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);

    struct sockaddr_in peeraddr;
    bzero(&peeraddr, sizeof(peeraddr));
    peeraddr.sin_family = AF_INET;
    peeraddr.sin_addr.s_addr = inet_addr(argv[1]);
    // peeraddr.sin_port = htons(atoi(argv[2]));
    peeraddr.sin_port = htons(60001);

    printf("[%s : %hu]", inet_ntoa(peeraddr.sin_addr), peeraddr.sin_port);
    char buf[128];
    while(1)
    {
        printf("开启发送\n");
        bzero(&buf, sizeof(buf));
        fgets(buf, sizeof(buf), stdin);
        sendto(sockfd, buf, sizeof(buf), 0, (struct sockaddr *)&peeraddr, sizeof(peeraddr));
    }
    return 0;
}


